/*
 * XMLDocument.cpp
 *
 *  Created on: 2010-3-25
 *      Author: wenjian
 */

#include "XMLDocument.h"
#include "XMLElement.h"

using namespace std;

namespace Try {

  XMLDocument::XMLDocument()
    :rootElement(NULL){

  }

  XMLDocument::~XMLDocument() {
    std::vector<XMLElement*>::iterator eit = allElements.begin();
    for(;eit!=allElements.end();eit++){
      delete *eit;
    }

    std::vector<XMLAttribute*>::iterator ait = allAttributes.begin();
    for(;ait!=allAttributes.end();ait++){
      delete *ait;
    }

  }

  /**
   * 返回根XMLElement元素
   */
  XMLElement* XMLDocument::getRootElement() const{
    if(rootElement==NULL){
      throw "The root element does not exist";//根元素不存在
    }
    return rootElement;
  }

  /**
   * 设置根XMLElement元素
   */
  XMLElement* XMLDocument::setRootElement(XMLElement* e){
    if(!containsElement(e)){
      throw "Elements created in this document is not received";//此元素不是此文档创建的
    }
    if(e == rootElement || e->getParent()!=NULL){
      throw "This element is the parent node already exists";//此元素已经存在父节点
    }
    rootElement = e;
    return e;
  }

  /**
   * 创建一个XMLElement元素
   */
  XMLElement* XMLDocument::newElement(const char* name){
    XMLElement* e = new Try::XMLElement(this, name);
    allElements.push_back(e);
    return e;
  }

  /**
   * 创建一个XMLAttribute属性
   */
  XMLAttribute* XMLDocument::newAttribute(const char* name, const char* value){
    XMLAttribute* a = new XMLAttribute(name, value);
    allAttributes.push_back(a);
    return a;
  }

}
